<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\analysis\stat\kuaishou;

use app\model\mongo\MongoKsAccountPicStatModel;
use app\model\mongo\MongoKsClientPicStatModel;
use app\service\analysis\KuaiShouTrait;
use app\service\analysis\stat\StatInterface;
use app\service\analysis\stat\StatService;

final class PicStatService extends StatService implements StatInterface
{
    use KuaiShouTrait;


    /**
     * 客户汇总查询.
     * @param array $where 查询语句
     */
    public function getClientStat(array $where = []): array
    {
        $model = new MongoKsAccountPicStatModel();
        $res = $model->cmd([
            'aggregate' => $model->getTable(),
            'pipeline' => [
                [
                    '$match' => $where,
                ],
                [
                    '$group' => [
                        '_id' => null,
                        'totalCost' => ['$sum' => '$cost'],
                    ],
                ],
                [
                    '$project' => [
                        '_id' => 1,
                        'totalCost' => 1,
                    ],
                ],
            ],
            'cursor' => new \stdClass(),
            'explain' => false,
        ]);
        $data = $res[0] ?? [];
        return [
            'cost' => $this->getTotalCost($data),
        ];
    }

    /**
     * 视频汇总查询.
     * @param array $where 查询语句
     */
    public function getPicStat(array $where = []): array
    {
        $model = new MongoKsClientPicStatModel();
        $res = $model->cmd([
            'aggregate' => $model->getTable(),
            'pipeline' => [
                [
                    '$match' => $where,
                ],
                [
                    '$group' => [
                        '_id' => null,
                        'totalCost' => ['$sum' => '$cost'],
                    ],
                ],
                [
                    '$project' => [
                        '_id' => 1,
                        'totalCost' => 1,
                    ],
                ],
            ],
            'cursor' => new \stdClass(),
            'explain' => false,
        ]);
        $data = $res[0] ?? [];
        return [
            'cost' => $this->getTotalCost($data),
        ];
    }

    /**
     * 获取消耗.
     *
     * @param array $data 数据
     */
    private function getTotalCost(array $data = []): float
    {
        $cost = $data['totalCost'] ?? 0;
        return floatval(bcadd(strval($cost), '0', 3));
    }
}
